/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.velocityme.entity;

import com.velocityme.enums.Permission;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.ManyToMany;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;

/**
 *
 * @author rcrida
 */
@Entity
@NamedQueries( {
    @NamedQuery(name="findAllRoles",
                query="SELECT o FROM Role o WHERE o.deleted = FALSE ORDER BY o.name"),
    @NamedQuery(name="findRolesByUserAndSearch",
                query="SELECT r FROM Search s, IN (s.searchLevels) l, IN (l.nodes) n, UserAccess ua, Role r " +
                      "WHERE (ua.user = :user AND ua.role = r AND " +
                      "      ((s = :search AND r.recursive = TRUE AND ua.node = n) OR (ua.node = :node AND r.recursive = FALSE)))"),
    @NamedQuery(name="findRolesByGroupAndSearch",
                query="SELECT r FROM Search s, IN (s.searchLevels) l, IN (l.nodes) n, GroupAccess ga, IN (ga.group.users) gu, Role r " +
                      "WHERE (gu = :user AND ga.role = r AND " +
                      "      ((s = :search AND r.recursive = TRUE AND ga.node = n) OR (ga.node = :node AND r.recursive = FALSE)))")
})
public class Role extends Node {
    private static final long serialVersionUID = 1L;

    private boolean recursive;
    
    private HashSet<Permission> permissions = new HashSet<Permission>();
    
    @OneToMany(mappedBy = "role")
    private Set<UserAccess> userAccesses = new HashSet<UserAccess>();

    @OneToMany(mappedBy = "role")
    private Set<GroupAccess> groupAccesses = new HashSet<GroupAccess>();

    @ManyToMany(mappedBy = "responsibleRoles")
    private Set<Transition> responsibleTransitions = new HashSet<Transition>();

    @ManyToMany(mappedBy = "interestedRoles")
    private Set<TaskStateMachine> interestedStateMachines = new HashSet<TaskStateMachine>();

    public Role() {
    }
    
    public Role(Node parentNode, String name, String description, HashSet<Permission> permissions, boolean recursive) {
        super(parentNode, name, description);
        this.permissions = permissions;
        this.recursive = recursive;
    }

    public Set<Permission> getPermissions() {
        return permissions;
    }

    public void setPermissions(HashSet<Permission> permissions) {
        this.permissions = permissions;
    }

    public boolean isRecursive() {
        return recursive;
    }

    public void setRecursive(boolean recursive) {
        this.recursive = recursive;
    }

    public Set<TaskStateMachine> getInterestedStateMachines() {
        return interestedStateMachines;
    }

}
